package com.aliyun.oss.ws;

import com.aliyun.oss.config.GetHttpSessionConfig;
import com.aliyun.oss.pojo.Message;
import com.aliyun.oss.utils.MessageUtils;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
@Component
public class ChatEndpoint {
    private static final Map<String,Session> sessions = new java.util.concurrent.ConcurrentHashMap<>();
    HttpSession httpSession;
    private String currentUser;
    //    建立连接
    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) throws IOException {
//         1.将session保存起来,用户名为键
        httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());
        currentUser = (String) httpSession.getAttribute("user");
//        为了防止用户重复登录
        if(sessions.containsKey(currentUser)){
            Session session1 = sessions.get(currentUser);
            if(session1.isOpen()){
                session1.close();
            }
            sessions.remove(currentUser);
        }
        sessions.put(currentUser,session);
//        2.广播消息，告诉所有人有人上线了
        String message = MessageUtils.getMessage(true, null, getFirends());
        broadcastAllUsers(message);
        System.out.println("用户上线了："+currentUser);
    }
//  浏览器发送消息到服务器，方法调用
//    李四-》张三
//    message格式：{"toName":"张三","message":"你好"}
//    返回格式{"system":false,"fromName":"李四","message":"你好"}
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
//      将消息推送给指定的用户，先将json转换为message对象
        Message message1 = MessageUtils.jsonToMessage(message);
        String toName = message1.getToName();
        String message2 = message1.getMessage();
        currentUser = (String) httpSession.getAttribute("user");
        String message3 = MessageUtils.getMessage(false, currentUser, message2);
        sessions.get(toName).getAsyncRemote().sendText(message3);
        System.out.println("用户发送消息："+currentUser+"给："+toName+"消息："+message2);

    }
//    断开websocket连接

    @OnClose
    public void onClose(Session session) throws IOException {
//        1.从sessions中删除用户
        currentUser = (String) httpSession.getAttribute("user");
        sessions.remove(currentUser);
//        2.广播通知所有用户
        String message1 = MessageUtils.getMessage(true, null, getFirends());
        broadcastAllUsers(message1);
        System.out.println("用户下线了：" + currentUser);
    }

//    广播方法
    private void broadcastAllUsers(String message) throws IOException {
        Set<Map.Entry<String, Session>> entries = sessions.entrySet();
        for (Map.Entry<String, Session> entry : entries) {
            Session session = (Session) entry.getValue();
            session.getAsyncRemote().sendText(message);
        }
    }
//    获取所有用户名
    public Set getFirends(){
        Set<String> strings = sessions.keySet();
        return strings;
    }
}
